package pro.common;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = "/wyn/*")
public class CoreFilter implements Filter {

    public void destroy() {
        // 当过滤器被销毁的时候被执行
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) 
            throws ServletException, IOException {
        // 将 req 强制类型转换为 HttpServletRequest 对象
        HttpServletRequest request =(HttpServletRequest) req;
        // 将 resp 强制类型转换为 HttpServletResponse 对象
        HttpServletResponse response = (HttpServletResponse) resp;
        // getRequestURI 方法得到的是：/wyl/login.jsp
        // request.getRequestURI();
        // getRequestURL 方法得到的是：http://localhost:8080/wyn/login.jsp
        // request.getRequestURL();
        String uri = request.getRequestURI();
        if("/wyn/login.jsp".equals(uri)||uri.endsWith(".css")){
            // 此时被拦截的是登录页或样式表，允许通过
            chain.doFilter(req,resp);
            return;
        }
        // 获取 session
        HttpSession session = request.getSession();
        Object uid = session.getAttribute("UID");
        if(uid==null){
            // 说明没有登录
            response.sendRedirect("/wyn/login.jsp");
            return;
        }
        // 说明用户已经登录过，允许通过
        chain.doFilter(req,resp);

    }

    public void init(FilterConfig config) throws ServletException {
        //初始化函数
    }

}
